package ch7.DiningPhilosophers;

/**
 * 使用粗锁发来消除产生死锁的必要条件之一：占用并等待资源
 * 使用一个粗粒度的锁代替原先的多个粒度较细的锁，这样设计的线程只需要申请一个锁即可
 * 避免了多个线程申请了不同的锁，并且等待其他线程释放锁，造成的死锁
 * 但是粗粒度锁明显地降低了并发性并可能导致资源浪费
 * 因此，粗锁法的适用范围比较有限
 */

import util.Debug;

public class GlobalLckBasedPhilosopher extends AbstractPhilosopher{
    private final static Object GLOBAL_LOCK = new Object();

    public GlobalLckBasedPhilosopher(int id, Chopstick left, Chopstick right) {
        super(id, left, right);
    }

    @Override
    public void eat() {
        synchronized (GLOBAL_LOCK) {
            Debug.info("%s is picking up %s on his left...%n", this, left);
            left.pickUp();
            Debug.info("%s is picking up %s on his right...%n", this, right);
            right.pickUp();
            doEat();
            right.putDown();
            left.putDown();
        }
    }
}
